package com.vr.xuecheng.media.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vr.xuecheng.media.mapper.MediaProcessMapper;
import com.vr.xuecheng.media.model.entity.MediaFiles;
import com.vr.xuecheng.media.model.entity.MediaProcess;
import com.vr.xuecheng.media.service.IMediaProcessService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hzh
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MediaProcessServiceImpl extends ServiceImpl<MediaProcessMapper, MediaProcess> implements IMediaProcessService {

    private final MediaProcessMapper mediaProcessMapper;
    private final Tika tika = new Tika();

    @Override
    public void addWaitingTask(MediaFiles mediaFiles) {
        // 只将avi视频添加待处理数据库里，让后进行转码
        // 判断文件类型
        MediaProcess mediaProcess = MediaProcess.builder()
                .fileId(mediaFiles.getFileId())
                .filename(mediaFiles.getFilename())
                .bucket(mediaFiles.getBucket())
                .filePath(mediaFiles.getFilePath())
                .url(mediaFiles.getUrl())
                .status("1")
                .failCount(0)
                .build();
        if ("video/x-msvideo".equals(tika.detect(mediaFiles.getFilename()))) {
            mediaProcessMapper.insert(mediaProcess);
        }
    }

    @Override
    public List<MediaProcess> getMediaProcessList(int shardIndex, int shardTotal, int processorCount) {
        return mediaProcessMapper.getMediaProcessList(shardIndex, shardTotal, processorCount);
    }

    @Override
    public boolean startTask(Long id) {
        return mediaProcessMapper.updateForStartTask(id)>0;
    }

    @Override
    public boolean updateMediaProcessFinishStatus(MediaProcess mediaProcess) {
        return mediaProcessMapper.updateById(mediaProcess)>0;
    }


}
